package cn.shoptnt.framework.elasticsearch.core;

import cn.shoptnt.framework.elasticsearch.ElasticBuilderUtil;
import cn.shoptnt.framework.elasticsearch.ElasticJestConfig;
import cn.shoptnt.framework.elasticsearch.ElasticOperationUtil;
import cn.shoptnt.framework.elasticsearch.EsSettings;
import io.searchbox.client.JestClient;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 初始es索引
 * @author Administrator
 */
@Component
public class EsIndexInit {

    @Autowired
    private ElasticJestConfig elasticJestConfig;

    private final Logger logger = LoggerFactory.getLogger(getClass());


    public void initEs(){
        JestClient jestClient=null;
         jestClient = ElasticBuilderUtil.buildJestClient(elasticJestConfig.getClusterIps(),
                 elasticJestConfig.getClusterRestPort(),
                 elasticJestConfig.getScheme(),
                 elasticJestConfig.getUsername(),
                 elasticJestConfig.getPassword());

        //拼装索引名称
        String goodsIndices = elasticJestConfig.getIndexName() + "_" + EsSettings.GOODS_INDEX_NAME;
        String ptIndices = elasticJestConfig.getIndexName() + "_" + EsSettings.PINTUAN_INDEX_NAME;

        //设置分片数
        Settings settings = Settings.builder().put("number_of_shards",5).put("number_of_replicas",3).build();

        //获取es版本号
        ElasticBuilderUtil.version = ElasticOperationUtil.version(jestClient);

        logger.debug("ElasticSearch verison is {}",ElasticBuilderUtil.version);

        //检测商品索引是否存在
        if (!ElasticOperationUtil.indicesExists(jestClient, goodsIndices)) {

            logger.debug("系统检测到索引{}不存在，创建索引和Mapping",goodsIndices);

            //创建Goods映射
            CreateIndexRequest goodsRequest = new CreateIndexRequest(goodsIndices);
            //设置分片数
            goodsRequest.settings(settings);
            //创建映射
            ElasticOperationUtil.createIndex(jestClient,goodsIndices,ElasticBuilderUtil.createGoodsMapping());
        }else {
            logger.debug("系统检测到索引{}已经存在",goodsIndices);
        }

        //检测拼团索引是否存在
        if (!ElasticOperationUtil.indicesExists(jestClient, ptIndices)){
            logger.debug("系统检测到索引{}不存在，创建索引和Mapping",ptIndices);
            //创建拼团映射
            CreateIndexRequest ptRequest = new CreateIndexRequest(ptIndices);
            //设置分片数
            ptRequest.settings(settings);
            //创建映射
            ElasticOperationUtil.createIndex(jestClient,ptIndices,ElasticBuilderUtil.createPingTuanMapping());
        }else {
            logger.debug("系统检测到索引{}已经存在",ptIndices);
        }

    }

}
